package com.tutu.mybatis.dynamic.datasource.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author qyy
 * @date 2021/4/20 8:41
 */
@Aspect
@Order(1)
@Component
public class ApiLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(ApiLogAspect.class);

    @Resource
    HttpServletRequest request;

    @Around("apiLogPointCut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        StopWatch clock = null;
        //这边要保证不影响正常业务执行
        try {
            try {
                clock = new StopWatch();
                clock.start();
            } catch (Exception ignore) {
            }
            return proceedingJoinPoint.proceed();
        } finally {
            try {
                if (clock != null && clock.isRunning()) {
                    clock.stop();
                    logger.info("接口:{} 耗时:{}ms", request.getRequestURI(), clock.getTotalTimeMillis());
                }
            } catch (Exception ignore) {
            }
        }
    }

    @Pointcut("@within(com.tutu.mybatis.dynamic.datasource.annotation.ApiLog) && !@annotation(com.tutu.mybatis.dynamic.datasource.annotation.IgnoreApiLog)")
    public void apiLogPointCut() {

    }
}
